
package cn.myzf.fort.access.accesscommon.core;



import java.util.concurrent.*;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * 线程池执行服务对象.
 * 无界队列
 * 由于sock5任务数是不确定的
 */
public final class ExecutorServices {

    private final ThreadPoolExecutor threadPoolExecutor;

    private final BlockingQueue<Runnable> workQueue;

    private final static String namingPattern = "sock5-dynamic";

    public ExecutorServices() {
        workQueue = new SynchronousQueue<>();
        threadPoolExecutor = new ThreadPoolExecutor(0, Integer.MAX_VALUE, 60L, TimeUnit.MINUTES, workQueue,
                createThreadFactory(namingPattern));
    }
    
    /**
     * 创建线程池服务对象.
     *
     * @return 线程池服务对象
     */
    private ThreadFactory createThreadFactory(String namingPattern) {
        return new NameSpaceThreadFactory(namingPattern);
    }

    public ExecutorService createExecutorService() {
        return threadPoolExecutor;
    }
    
    public boolean isShutdown() {
        return threadPoolExecutor.isShutdown();
    }
    
    /**
     * 获取当前活跃的线程数.
     *
     * @return 当前活跃的线程数
     */
    public int getActiveThreadCount() {
        return threadPoolExecutor.getActiveCount();
    }
    
    /**
     * 获取待执行任务数量.
     *
     * @return 待执行任务数量
     */
    public int getWorkQueueSize() {
        return workQueue.size();
    }


    class NameSpaceThreadFactory implements ThreadFactory {
        private final AtomicInteger threadNumber = new AtomicInteger(1);
        private final String namePrefix;

        public NameSpaceThreadFactory(String namePrefix) {
            this.namePrefix = namePrefix + "-";
        }

        @Override
        public Thread newThread(Runnable r) {
            Thread t = new Thread(r, namePrefix + threadNumber.getAndIncrement());
            if (t.isDaemon())
                t.setDaemon(true);
            if (t.getPriority() != Thread.NORM_PRIORITY)
                t.setPriority(Thread.NORM_PRIORITY);
            return t;

        }
    }
}
